package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class PaymentController {

    Logger logger = LoggerFactory.getLogger(PaymentController.class);

    @Value("${server.port}")
    private String serverPost;

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        logger.info("Payment:{}", payment);

        int result = paymentService.create(payment);
        logger.info("----------------插入结果：{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功,serverPost:" + serverPost, result);
        } else {
            return new CommonResult(444, "插入数据库失败");
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {

        Payment payment = paymentService.getPaymentById(id);
        logger.info("----------------查询结果 hello ：{}", payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功,serverPost:" + serverPost, payment);
        } else {
            return new CommonResult(444, "没有对应记录，查询ID:" + id);
        }
    }

    @GetMapping("/payment/discovery")
    public DiscoveryClient discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            logger.info("*******element:" + element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            logger.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }
    @GetMapping("/payment/lb")
    public String getPaymentLB(){

        return serverPost;
    }


    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        logger.info("执行{}的paymentFeignTimeout",serverPost);
        try {
            // 暂停几秒钟线程
            TimeUnit.SECONDS.sleep(3);
        } catch(InterruptedException e){
            e.printStackTrace();
        }
        return serverPost;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        return "hi ,i'm paymentZipkin server fall back ,welcome";
    }
}
